<template>
  <div id="permission">
    <el-tree
      ref="tree"
      :data="routeTree"
      show-checkbox
      default-expand-all
      node-key="name"
      highlight-current
      :props="defaultProps"
    >
    </el-tree>

    <el-card> 当前选中：{{ selectedNodes }} </el-card>

    <div class="buttons">
      <el-button @click="getCheckedNodes">通过 node 获取</el-button>
      <el-button @click="setChecked">设置</el-button>
    </div>
  </div>
</template>

<script>
import { asyncRoutes } from '@/router'
export default {
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: child => child.meta.title
      },
      selectedNodes: []
    }
  },

  computed: {
    routeTree() {
      return this.formatRoutes(asyncRoutes)
    }
  },

  methods: {
    // 格式化路由数组结构，处理只有一个children和hidden的情景
    formatRoutes(routesArr) {
      return routesArr
        .filter(item => {
          if (item.children && item.children.length === 1) {
            return !(item.hidden || item.children[0].hidden)
          }
          return !item.hidden
        })
        .map(item => {
          // 子叶存在 但是只有一个时
          if (item.children && item.children.length === 1) {
            return item.children[0]
          }
          // 子叶有多个
          if (item.children) {
            item.children = this.formatRoutes(item.children)
          }
          return item
        })
    },

    getCheckedNodes() {
      this.selectedNodes = this.$refs.tree
        .getCheckedNodes(false, true)
        .map(item => {
          return item.name
        })
    },

    setChecked() {
      this.$refs.tree.setCheckedKeys(['Home'])
    }
  }
}
</script>
<style lang="scss" scoped></style>
